import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
// import { Separator } from "@/components/ui/separator"
import { ArrowLeft, Clock, Trophy, Users, Zap, Target, Coins, Shield } from 'lucide-react'
import { MatchDetail as MatchDetailType, Hero } from '../types/dota'
import { openDotaAPI } from '../services/api'
import { ItemImage } from './ItemImage'
import AdvantageChart from './AdvantageChart'
import PlayerEconomyCurveChart from './PlayerEconomyCurveChart'
// import { getItemName, getItemDisplayName } from '../constants/items'

interface MatchDetailProps {
  matchId: string
  onBack: () => void
}



export default function MatchDetail({ matchId, onBack }: MatchDetailProps) {
  const [matchDetail, setMatchDetail] = useState<MatchDetailType | null>(null)
  const [heroes, setHeroes] = useState<{ [key: number]: Hero }>({})
  // const [items, setItems] = useState<any>({})
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        setError(null)

        // 并行获取比赛详情、英雄数据和道具数据
        const [matchData, heroData, itemData] = await Promise.all([
          openDotaAPI.getMatchDetail(matchId),
          openDotaAPI.getHeroes(),
          openDotaAPI.getItems()
        ])

        setMatchDetail(matchData)
        
        // 将英雄数据转换为以ID为键的对象
        const heroMap = heroData.reduce((acc: { [key: number]: Hero }, hero: Hero) => {
          acc[hero.id] = hero
          return acc
        }, {})
        setHeroes(heroMap)
        // setItems(itemData)
        console.log('Items data loaded:', itemData)
        console.log('Items data keys:', Object.keys(itemData))
      } catch (err) {
        console.error('Error loading data:', err)
        setError(err instanceof Error ? err.message : '获取比赛详情失败')
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [matchId])

  const formatDuration = (duration: number) => {
    const minutes = Math.floor(duration / 60)
    const seconds = duration % 60
    return `${minutes}:${seconds.toString().padStart(2, '0')}`
  }

  const formatDate = (startTime: number) => {
    const date = new Date(startTime * 1000)
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  }

  const getGameMode = (gameMode: number) => {
    const modes: { [key: number]: string } = {
      1: 'All Pick',
      2: 'Captain\'s Mode',
      3: 'Random Draft',
      4: 'Single Draft',
      5: 'All Random',
      16: 'Captain\'s Draft',
      22: 'Ranked All Pick',
      23: 'Turbo'
    }
    return modes[gameMode] || `Mode ${gameMode}`
  }

  const getHeroImageUrl = (heroName: string) => {
    const cleanName = heroName.replace('npc_dota_hero_', '')
    return `http://cdn.dota2.com/apps/dota2/images/heroes/${cleanName}_lg.png`
  }



  if (loading) {
    return (
      <Card className="modern-card">
        <CardHeader>
          <div className="flex items-center space-x-4">
            <Button variant="ghost" size="sm" onClick={onBack}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              返回
            </Button>
            <CardTitle className="text-xl font-bold text-foreground">
              比赛详情
            </CardTitle>
          </div>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center py-12">
            <div className="flex items-center space-x-3">
              <div className="loading-spinner w-6 h-6"></div>
              <span className="text-muted-foreground">加载比赛详情中...</span>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  if (error) {
    return (
      <Card className="modern-card border-destructive/50 bg-destructive/5">
        <CardHeader>
          <div className="flex items-center space-x-4">
            <Button variant="ghost" size="sm" onClick={onBack}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              返回
            </Button>
            <CardTitle className="text-xl font-bold text-destructive">
              加载失败
            </CardTitle>
          </div>
        </CardHeader>
        <CardContent>
          <div className="text-center py-12">
            <div className="text-4xl mb-4">⚠️</div>
            <div className="text-lg font-medium text-destructive mb-2">
              获取比赛详情失败
            </div>
            <div className="text-sm text-muted-foreground">
              {error}
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  if (!matchDetail) {
    return null
  }

  const radiantPlayers = matchDetail.players.filter(player => player.player_slot < 128)
  const direPlayers = matchDetail.players.filter(player => player.player_slot >= 128)

  return (
    <div className="space-y-6">
      {/* 返回按钮和比赛基本信息 */}
      <Card className="modern-card">
        <CardHeader>
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button variant="ghost" size="sm" onClick={onBack}>
                <ArrowLeft className="h-4 w-4 mr-2" />
                返回
              </Button>
              <div>
                <CardTitle className="text-2xl font-bold text-foreground flex items-center space-x-2">
                  <Trophy className="h-6 w-6" />
                  <span>比赛 #{matchDetail.match_id}</span>
                </CardTitle>
                <CardDescription className="text-muted-foreground mt-1">
                  {formatDate(matchDetail.start_time)} • {getGameMode(matchDetail.game_mode)}
                </CardDescription>
              </div>
            </div>
            <Badge 
              variant={matchDetail.radiant_win ? "default" : "destructive"}
              className={`text-lg px-4 py-2 ${
                matchDetail.radiant_win 
                  ? 'bg-green-600 hover:bg-green-700' 
                  : 'bg-red-600 hover:bg-red-700'
              } text-white font-medium`}
            >
              {matchDetail.radiant_win ? '天辉胜利' : '夜魇胜利'}
            </Badge>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
            <div className="flex items-center space-x-2">
              <Clock className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm">
                <span className="font-medium">时长:</span> {formatDuration(matchDetail.duration)}
              </span>
            </div>
            <div className="flex items-center space-x-2">
              <Users className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm">
                <span className="font-medium">玩家:</span> {matchDetail.human_players}
              </span>
            </div>
            <div className="flex items-center space-x-2">
              <Target className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm">
                <span className="font-medium">比分:</span> {matchDetail.radiant_score} - {matchDetail.dire_score}
              </span>
            </div>
            <div className="flex items-center space-x-2">
              <Zap className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm">
                <span className="font-medium">首杀:</span> {Math.floor(matchDetail.first_blood_time / 60)}:{(matchDetail.first_blood_time % 60).toString().padStart(2, '0')}
              </span>
            </div>
            {matchDetail.leagueid && matchDetail.leagueid > 0 && (
              <div className="flex items-center space-x-2">
                <Trophy className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm">
                  <span className="font-medium">联赛:</span> {matchDetail.leagueid}
                </span>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 经济/经验曲线 */}
      <Card className="modern-card">
        <CardHeader>
          <CardTitle className="text-xl font-bold flex items-center space-x-2">
            <Zap className="h-5 w-5" />
            <span>经济/经验曲线</span>
          </CardTitle>
          <CardDescription>每分钟的优势变化（天辉为正，夜魇为负）</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <AdvantageChart title="经济优势（每分钟）" data={matchDetail.radiant_gold_adv || []} />
            <AdvantageChart title="经验优势（每分钟）" data={matchDetail.radiant_xp_adv || []} />
          </div>
        </CardContent>
      </Card>

      {/* 玩家经济曲线 */}
      <Card className="modern-card">
        <CardHeader>
          <CardTitle className="text-xl font-bold flex items-center space-x-2">
            <Coins className="h-5 w-5" />
            <span>玩家经济曲线</span>
          </CardTitle>
          <CardDescription>20位玩家的经济发展曲线对比</CardDescription>
        </CardHeader>
        <CardContent>
          <PlayerEconomyCurveChart 
            players={matchDetail.players} 
            duration={matchDetail.duration}
            title="玩家净值变化曲线"
          />
        </CardContent>
      </Card>

      {/* 天辉队伍 */}
      <Card className="modern-card">
        <CardHeader>
          <CardTitle className="text-xl font-bold text-green-600 flex items-center space-x-2">
            <Shield className="h-5 w-5" />
            <span>天辉 (Radiant)</span>
            {matchDetail.radiant_win && <Trophy className="h-4 w-4 text-yellow-500" />}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>玩家</TableHead>
                <TableHead className="text-center">英雄</TableHead>
                <TableHead className="text-center">等级</TableHead>
                <TableHead className="text-center">KDA</TableHead>
                <TableHead className="text-center">补刀/反补</TableHead>
                <TableHead className="text-center">GPM/XPM</TableHead>
                <TableHead className="text-center">伤害</TableHead>
                <TableHead className="text-center">装备</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {radiantPlayers.map((player) => {
                const hero = heroes[player.hero_id]
                return (
                  <TableRow key={player.player_slot}>
                    <TableCell>
                      <div className="font-medium">
                        {player.personaname || player.name || `Player ${player.player_slot}`}
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="flex items-center justify-center space-x-2">
                        {hero && (
                          <img
                            src={getHeroImageUrl(hero.name)}
                            alt={hero.localized_name}
                            className="w-12 h-8 rounded border border-border object-cover"
                          />
                        )}
                        <span className="text-sm font-medium">
                          {hero?.localized_name || 'Unknown'}
                        </span>
                      </div>
                    </TableCell>
                    <TableCell className="text-center font-medium">
                      {player.level}
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="font-mono text-sm">
                        <span className="text-green-600 font-semibold">{player.kills}</span>
                        <span className="text-muted-foreground mx-1">/</span>
                        <span className="text-red-600 font-semibold">{player.deaths}</span>
                        <span className="text-muted-foreground mx-1">/</span>
                        <span className="text-blue-600 font-semibold">{player.assists}</span>
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="text-sm">
                        <div>{player.last_hits}/{player.denies}</div>
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="text-sm">
                        <div className="font-medium">{player.gold_per_min}</div>
                        <div className="text-muted-foreground text-xs">{player.xp_per_min}</div>
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="text-sm">
                        <div className="font-medium">{player.hero_damage.toLocaleString()}</div>
                        <div className="text-muted-foreground text-xs">{player.tower_damage.toLocaleString()}</div>
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="flex items-center justify-center space-x-1">
                        {[player.item_0, player.item_1, player.item_2, player.item_3, player.item_4, player.item_5].map((itemId, index) => (
                          <div key={index} className="w-8 h-6 bg-muted rounded border border-border flex items-center justify-center">
                            {itemId !== 0 && (
                              <div className="relative">
                                <ItemImage itemId={itemId} />
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* 夜魇队伍 */}
      <Card className="modern-card">
        <CardHeader>
          <CardTitle className="text-xl font-bold text-red-600 flex items-center space-x-2">
            <Shield className="h-5 w-5" />
            <span>夜魇 (Dire)</span>
            {!matchDetail.radiant_win && <Trophy className="h-4 w-4 text-yellow-500" />}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>玩家</TableHead>
                <TableHead className="text-center">英雄</TableHead>
                <TableHead className="text-center">等级</TableHead>
                <TableHead className="text-center">KDA</TableHead>
                <TableHead className="text-center">补刀/反补</TableHead>
                <TableHead className="text-center">GPM/XPM</TableHead>
                <TableHead className="text-center">伤害</TableHead>
                <TableHead className="text-center">装备</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {direPlayers.map((player) => {
                const hero = heroes[player.hero_id]
                return (
                  <TableRow key={player.player_slot}>
                    <TableCell>
                      <div className="font-medium">
                        {player.personaname || player.name || `Player ${player.player_slot}`}
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="flex items-center justify-center space-x-2">
                        {hero && (
                          <img
                            src={getHeroImageUrl(hero.name)}
                            alt={hero.localized_name}
                            className="w-12 h-8 rounded border border-border object-cover"
                          />
                        )}
                        <span className="text-sm font-medium">
                          {hero?.localized_name || 'Unknown'}
                        </span>
                      </div>
                    </TableCell>
                    <TableCell className="text-center font-medium">
                      {player.level}
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="font-mono text-sm">
                        <span className="text-green-600 font-semibold">{player.kills}</span>
                        <span className="text-muted-foreground mx-1">/</span>
                        <span className="text-red-600 font-semibold">{player.deaths}</span>
                        <span className="text-muted-foreground mx-1">/</span>
                        <span className="text-blue-600 font-semibold">{player.assists}</span>
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="text-sm">
                        <div>{player.last_hits}/{player.denies}</div>
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="text-sm">
                        <div className="font-medium">{player.gold_per_min}</div>
                        <div className="text-muted-foreground text-xs">{player.xp_per_min}</div>
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="text-sm">
                        <div className="font-medium">{player.hero_damage.toLocaleString()}</div>
                        <div className="text-muted-foreground text-xs">{player.tower_damage.toLocaleString()}</div>
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="flex items-center justify-center space-x-1">
                        {[player.item_0, player.item_1, player.item_2, player.item_3, player.item_4, player.item_5].map((itemId, index) => (
                          <div key={index} className="w-8 h-6 bg-muted rounded border border-border flex items-center justify-center">
                            {itemId !== 0 && (
                              <div className="relative">
                                <ItemImage itemId={itemId} />
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  )
}